package com.zhao.dota.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhao.dota.common.task.BaseTask;
import com.zhao.dota.model.SpringScheduledCron;
import com.zhao.dota.service.SpringScheduledCronService;
import com.zhao.dota.struct.Result;
import com.zhao.dota.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskManagerController {

    @Resource
    private SpringScheduledCronService springScheduledCronService;

    @GetMapping("/")
    public Result<List<SpringScheduledCron>> getList(SpringScheduledCron springScheduledCron) {
        List<SpringScheduledCron> list = springScheduledCronService.list(Wrappers.query(springScheduledCron));
        return Result.success(list);
    }

    @PostMapping("/")
    public Result<Integer> save(SpringScheduledCron springScheduledCron) {
        springScheduledCronService.save(springScheduledCron);
        return Result.success(springScheduledCron.getId());
    }

    @GetMapping("/enable")
    public Result<Boolean> enable(Integer id) {
        boolean enable = springScheduledCronService.enable(id);
        return Result.success(enable);
    }

    @GetMapping("/disable")
    public Result<Boolean> disable(Integer id) {
        boolean disable = springScheduledCronService.disable(id);
        return Result.success(disable);
    }

    @GetMapping("/execute")
    public Result execute(Integer id) {
        SpringScheduledCron cron = springScheduledCronService.getById(id);
        if (cron != null) {
            try {
                BaseTask task = (BaseTask) SpringUtil.getBean(Class.forName(cron.getCronKey()));
                task.run();
                return Result.success();
            } catch (ClassNotFoundException | ClassCastException e) {
                log.error("立即执行任务失败", e);
                return Result.error(e.getMessage());
            }
        }
        return Result.error();
    }

}
